import { copyToClipboard } from '@/utils/format';
import { PageContainer } from '@ant-design/pro-components';
import Editor, { DiffEditor, loader } from '@monaco-editor/react';
import { Button, Collapse, Empty, Input, message, Modal, Space } from 'antd';
import { get, set } from 'lodash-es';
import { useRef, useState } from 'react';
import * as monaco from 'monaco-editor';
const { TextArea } = Input;

loader.config({ monaco });

const tabSize = 4;
const height = '500px';

const filterConfigKey = [
  {
    key: 'skill_attack_data',
    name: '技能-攻击技能',
  },
  {
    key: 'shak_skill',
    name: '技能-骨折技能',
  },
];

const DiffRender = ({ item, onExport: onPropsExport }) => {
  const diffEditorRef = useRef<any>(null);

  const handleEditorDidMount = (editor) => {
    diffEditorRef.current = editor;
  };

  // 导出配置
  const onExport = () => {
    const value = diffEditorRef.current.getModifiedEditor().getValue();
    try {
      const newValue = JSON.stringify(JSON.parse(value), null, tabSize);
      onPropsExport(newValue);
    } catch (error) {
      message.error('导出配置有误');
    }
  };

  return (
    <>
      <DiffEditor
        height={height}
        language="json"
        original={item.original}
        modified={item.modified}
        options={{
          tabSize,
        }}
        onMount={handleEditorDidMount}
      />
      <Button onClick={onExport}>导出配置</Button>
    </>
  );
};

export default () => {
  const [modalType, setModalType] = useState('');
  const [jsonValue, setJsonValue] = useState('');
  const [activeKey, setActiveKey] = useState<any>(['1']);
  const [list, setList] = useState<any>([{ key: '1' }]);

  const onCover = () => {
    list.forEach((item, i) => {
      if (i === 0) {
        return;
      }
      try {
        const modifiedVal = JSON.parse(item.modified);
        const mainVal = JSON.parse(list[0].value);
        filterConfigKey.forEach((obj) => {
          const val = get(modifiedVal, obj.key);
          set(mainVal, obj.key, val);
        });
        const newVal = JSON.stringify(mainVal, null, tabSize);
        console.log(newVal);
        item.modified = newVal;
      } catch (error) {
        console.log(error);
        message.error('覆盖失败');
      }
    });
    setList([...list]);
  };

  // 导入确认
  const handleOk = () => {
    let newList;
    let newValue;
    try {
      newValue = JSON.stringify(JSON.parse(jsonValue), null, tabSize);
    } catch (error) {
      message.error('导出配置有误');
      return;
    }
    if (modalType === '导入主配置') {
      list[0].value = newValue;
      newList = [...list];
    } else {
      newList = [
        ...list,
        {
          original: newValue,
          modified: newValue,
        },
      ];
    }
    setList(newList);
    setActiveKey(newList.length - 1);
    setModalType('');
  };

  const onInputChange = (e) => {
    setJsonValue(e.target.value);
  };

  // 导出配置
  const onExport = (val) => {
    copyToClipboard(val);
  };

  const items = list.map((item, i) => {
    if (i === 0) {
      if (!item.value) {
        return {
          ...item,
          label: '主配置待导入',
          children: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />,
        };
      }
      return {
        key: i,
        label: '主配置',
        children: (
          <Editor
            key={item.key}
            height={height}
            defaultLanguage="json"
            value={item.value}
            onChange={(value) => {
              item.value = value;
            }}
            options={{
              tabSize,
            }}
          />
        ),
      };
    }
    return {
      key: i,
      label: '连体配置' + i,
      children: (
        <>
          <DiffRender item={item} onExport={onExport} />
        </>
      ),
    };
  });

  return (
    <PageContainer
      header={{
        title: '',
      }}
    >
      <Collapse
        accordion
        items={items}
        activeKey={activeKey}
        onChange={setActiveKey}
      />
      <Space style={{ marginTop: 12 }}>
        <Button onClick={() => setModalType('导入主配置')}>导入主配置</Button>
        <Button onClick={() => setModalType('导入连体配置')}>
          导入连体配置
        </Button>
        <Button onClick={onCover}>覆盖配置</Button>
      </Space>
      <Modal
        title={modalType}
        open={!!modalType}
        onOk={handleOk}
        onCancel={() => setModalType('')}
        afterClose={() => {
          setJsonValue('');
          setModalType('');
        }}
      >
        <TextArea
          value={jsonValue}
          rows={10}
          onChange={onInputChange}
          allowClear
        />
      </Modal>
    </PageContainer>
  );
};
